#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import annotations

import shutil
import subprocess
import sys
from pathlib import Path


PKG_ROOT = Path(__file__).resolve().parents[1]


def run(cmd: list[str], *, cwd: Path) -> None:
    subprocess.run(cmd, cwd=str(cwd), check=True)


def main() -> None:
    out_dir = PKG_ROOT / "output"
    out_dir.mkdir(parents=True, exist_ok=True)

    derived = PKG_ROOT / "data" / "derived"
    panel = derived / "env_policy_city_year_with_wechat.csv"
    if not panel.exists():
        panel = derived / "env_policy_city_year.csv"
    if not panel.exists():
        raise SystemExit("Missing derived panels under `data/derived/`.")

    report = out_dir / "env_policy_results.md"
    fig_dir = out_dir / "figures"

    run(
        [
            sys.executable,
            str(PKG_ROOT / "code" / "analyze_env_policy_effects.py"),
            "--panel",
            str(panel),
            "--report",
            str(report),
            "--fig-dir",
            str(fig_dir),
        ],
        cwd=PKG_ROOT,
    )

    # Copy key manuscript figures for convenience (optional).
    paper_fig_dir = PKG_ROOT / "paper" / "figures"
    if paper_fig_dir.exists():
        out_paper_fig = out_dir / "paper_figures"
        out_paper_fig.mkdir(parents=True, exist_ok=True)
        for p in paper_fig_dir.glob("*.png"):
            shutil.copy2(p, out_paper_fig / p.name)


if __name__ == "__main__":
    main()
